package scatter.wxminiapp.rest.basic.mvc;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaMessage;
import cn.binarywang.wx.miniapp.constant.WxMaConstants;
import cn.binarywang.wx.miniapp.message.WxMaMessageRouter;
import cn.binarywang.wx.miniapp.message.WxMaXmlOutMessage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import scatter.common.rest.controller.SuperController;

import java.util.Objects;

/**
 * Created by yangwei
 * Created at 2021/11/22 20:48
 */
@Slf4j
@RestController
@RequestMapping("/wx/ma/portal/{appId}")
@Api(tags = "小程序对接入口相关接口")
public class MaPortalController extends SuperController {

    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private WxMaMessageRouter messageRouter;

    @ApiOperation("小程序接收来自微信的推送")
    @ResponseStatus(HttpStatus.OK)
    @PostMapping(produces = "application/xml; charset=UTF-8")
    public String post(@PathVariable String appId,
                       @RequestBody String requestBody,
                       String signature,
                       String timestamp,
                       String nonce,
                       @RequestParam(name = "encrypt_type", required = false) String encType,
                       @RequestParam(name = "msg_signature", required = false) String msgSignature) {

        this.wxMaService.switchover(appId);

        if (!wxMaService.checkSignature(timestamp, nonce, signature)) {
            throw new IllegalArgumentException("不合法的参数");
        }
        final boolean isJson = Objects.equals(wxMaService.getWxMaConfig().getMsgDataFormat(),
                WxMaConstants.MsgDataFormat.JSON);

        String out = null;
        if (encType == null) {
            // 明文传输的消息
            WxMaMessage inMessage;
            if (isJson) {
                inMessage = WxMaMessage.fromJson(requestBody);

            }else {
                inMessage = WxMaMessage.fromXml(requestBody);
            }
            WxMaXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }

            out = outMessage.toXml();
        } else if ("aes".equalsIgnoreCase(encType)) {
            // aes加密的消息
            WxMaMessage inMessage;
            if (isJson) {
                inMessage = WxMaMessage.fromEncryptedJson(requestBody, wxMaService.getWxMaConfig());
            }else {
                inMessage = WxMaMessage.fromEncryptedXml(requestBody, wxMaService.getWxMaConfig(),
                        timestamp, nonce, msgSignature);
            }


            log.debug("消息解密后内容为：{} ", inMessage.toString());
            WxMaXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }

            out = outMessage.toEncryptedXml(wxMaService.getWxMaConfig());
        }

        log.debug("组装回复信息：{}", out);
        return out;
    }

    private WxMaXmlOutMessage route(WxMaMessage message) {
        try {
            return this.messageRouter.route(message);
        } catch (Exception e) {
            log.error("路由消息时出现异常！", e);
        }

        return null;
    }

    @ApiOperation("小程序验证请求来自微信")
    @GetMapping(produces = "text/plain;charset=utf-8")
    @ResponseStatus(HttpStatus.OK)
    public String validate(@PathVariable String appId,
                          String signature,
                          String timestamp,
                          String nonce,
                          String echostr) {

        this.wxMaService.switchover(appId);

        return wxMaService.checkSignature(timestamp, nonce, signature) ? echostr: null;
    }
}
